import { isNull } from '../assets/js/utils/validate'
import GLOBAL     from '../assets/js/const/global'

const key = GLOBAL.SYSTEM.SHORTNAME + '-'

/**
 * 设置缓存
 * @param params
 */
export const setStore = (params = {}) => {
  let { name, content, type } = params
  name = key + name
  let obj = {
    dataType: typeof (content),
    content: content,
    type: type,
    datetime: new Date().getTime()
  }
  if (type === 'session') {
    window.sessionStorage.setItem(name, JSON.stringify(obj))
  } else if (type === 'local') {
    window.localStorage.setItem(name, JSON.stringify(obj))
  }
}

/**
 * 获取缓存
 * @param params
 * @returns {*}
 */
export const getStore = (params = {}) => {
  let { name, debug } = params
  let obj = {}
  let content
  name = key + name
  obj = window.sessionStorage.getItem(name)
  // 如果session中没取到,到local中取
  if (isNull(obj)) {
    obj = window.localStorage.getItem(name)
    if (isNull(obj)) {
      return
    }
  } else if (isNull(obj)) {
    return
  }

  obj = JSON.parse(obj)

  if (debug) {
    console.log(obj)
  }
  if (obj.dataType === 'string') {
    content = obj.content
  } else if (obj.dataType === 'number') {
    content = Number(obj.content)
  } else if (obj.dataType === 'boolean') {
    var Fn = Function
    content = new Fn('return ' + obj.content)()
  } else if (obj.dataType === 'object') {
    content = obj.content
  }
  return content
}

/**
 * 删除缓存
 */
export const removeStore = (params = {}) => {
  let {
    name,
    type
  } = params
  name = key + name
  if (type) {
    window.sessionStorage.removeItem(name)
  } else {
    window.localStorage.removeItem(name)
  }
}
